package com.wentao.mall.api

import com.wentao.mall.dao.MerchantDao
import com.wentao.mall.dao.ProductDao
import com.wentao.mall.dao.UserDao
import com.wentao.mall.entity.PageQuery
import com.wentao.mall.entity.ProTableResult
import com.wentao.mall.entity.simple
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@RestController
class MerchantController(
    val merchantDao: MerchantDao,
    val userDao: UserDao,
    val productDao: ProductDao
) {
    @GetMapping("/admin/merchant/list")
    fun list(pageQuery: PageQuery): ProTableResult {
        val page = merchantDao.findAll(pageQuery.toPageRequest())
        return page.simple()
    }

    @PostMapping("/admin/merchant/save")
    fun save(merchant: Merchant): Result {
        merchantDao.save(merchant)
        return Result.success()
    }

    @PostMapping("/admin/merchant/delete")
    fun delete(id: Int): Result {
        merchantDao.deleteById(id)
        return Result.success()
    }

    /**
     * 查看全部商户，包含用户是否点亮
     */
    @GetMapping("/api/user/{openId}/merchants")
    fun userMerchantList(@PathVariable openId: String): Result {
        val list = merchantDao.findAll()
        val user = userDao.findByOpenid(openId) ?: return Result.errorUserNotFound()

        val merchantLightUp = user.merchantLightUp

        val merchantVOs = list.map {
            if (it.id in merchantLightUp)
                it.toVO(LightUpStatus.DONE)
            else if (false)
                it.toVO(LightUpStatus.DOING)
            else
                it.toVO(LightUpStatus.NOT)
        }


        return Result.success(merchantVOs)
    }

    @GetMapping("/api/merchant/{merchantId}/products")
    fun merchantProducts(@PathVariable merchantId: String): List<Product> {
        val list = productDao.findByMerchantId(merchantId)
        return list
    }

}

@Entity
data class Merchant(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int?,
    val name: String?,
    val logo: String?,
    val type: MerchantType?,
    val principal: String?,
    val principalPhone: String?
) {

    fun toVO(lightUpStatus: LightUpStatus): MerchantVO {
        return MerchantVO(
            id = id,
            name = name,
            logo = logo,
            type = type,
            lightUpStatus = lightUpStatus
        )
    }

}

data class MerchantVO(
    val id: Int?,
    val name: String?,
    val logo: String?,
    val type: MerchantType?,
    val lightUpStatus: LightUpStatus = LightUpStatus.NOT
)

enum class MerchantType {
    CHANKANG, YUNJIAN
}

enum class LightUpStatus {
    NOT, DOING, DONE
}